package com.zoe.sec03oauth2.service;

import com.zoe.sec03oauth2.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @Author Zoe
 * @Date: 2021/03/29
 * @Description
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserDao dao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username.isEmpty()) {
            throw new UsernameNotFoundException("用户名不可为空");
        }
        com.zoe.sec03oauth2.entity.User userByUsername = dao.getUserByUsername(username);
        if (userByUsername == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询用户的权限
        List<String> permissions = dao.findPermissionsByUserId(userByUsername.getId());

        String[] pmsArray = permissions.toArray(new String[permissions.size()]);

        System.out.println(Arrays.toString(pmsArray));

        // 查询用户的角色
        List<String> roleByUserId = dao.findRoleByUserId(userByUsername.getId());

        String[] roleArray = roleByUserId.toArray(new String[roleByUserId.size()]);

        System.out.println(Arrays.toString(roleArray));

        UserDetails build = User.withUsername(userByUsername.getUserName())
            .password(userByUsername.getPassword())
            .authorities(pmsArray)
            .roles(roleArray)
            .build();
        return build;
    }
}
